import React,{useState} from 'react'
import IconMap from 'components/IconMap';
import { Button } from 'antd';
import { loginRule } from 'utils/rules'





const SmCodeLogin = ({ FormItem, Input }) => {
  const [disabled, setDisabled] = useState(true);
  const [currentStatus, setCurrentStatus] = useState(true);
  let [currentTime, setCurrentTime] = useState(5);

    // 检测手机号码输入是否成功
    const checkedMobile = async (val) => {
      // 获取手机验证的结果
      try {
        const data = await form.validateFields(['mobile'])
        setDisabled(false)
      } catch (error) {
        setDisabled(true)
      }
    }

    // 倒计时处理
    const runTime = () => {
      const timer = setInterval(() => {
        if(currentTime === 0) {
          clearInterval(timer);
          setCurrentStatus(true);
          setDisabled(false);
          setCurrentTime(5)
          return 
        }
        setCurrentTime(--currentTime)
      }, 1000)
    }

    const _sendSmCode = () => {
      setCurrentStatus(false)
      setDisabled(true);
      runTime();
    }    

  return (
    <>
      <FormItem name="mobile" rules={loginRule.mobileRule} hasFeedback>
        <Input placeholder="请输入手机号码" prefix={IconMap.mobileIcon} onChange={checkedMobile}/>
      </FormItem>
      <FormItem name="code" rules={loginRule.codeRule} hasFeedback>
        <Input
          placeholder="请输入验证码"
          prefix={IconMap.codeIcon}
          
          addonAfter={<Button
            disabled={disabled}
            onClick={_sendSmCode}
          >{
            currentStatus ? '发送验证码' : `${currentTime}秒后重新发送`

          }</Button>}
        />
      </FormItem>
    </>
  )
}

export default SmCodeLogin;